package controllers;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import models.Setting;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import services.SettingService;
import services.SynchronizationService;
import views.html.settings.*;

public class Settings extends Controller {
	
	private static final SettingService settingService = SettingService.getService();
	private static final SynchronizationService synchService = SynchronizationService.getService();
	public static final String SETTING_INPUT_NAME_PREFIX = "s:";
	
	public static Result listSettings() {
		synchronizeSettings();
		List<Setting> settings = Setting.find.all();
		return ok(list.render(settings));
	}
	
	public static Result updateSettings() {
		Map<String, String> data = Form.form().bindFromRequest().data();
		Iterator<String> keyIterator = data.keySet().iterator();
		String key;
		Setting setting;
		while (keyIterator.hasNext()) {
			key = keyIterator.next();
			if (key.startsWith(SETTING_INPUT_NAME_PREFIX)) {
				setting = Setting.find.byId(key.substring(SETTING_INPUT_NAME_PREFIX.length()));
				if (setting != null) {
					setting.setValue(data.get(key));
					setting.save();
				}
			}
		}
		synchService.synchronizeRemoteResources();
		return redirect(controllers.routes.Settings.listSettings());
	}
	
	private static void synchronizeSettings() {
		settingService.synchronizeSettings();
	}
	
}
